package net.concurrent;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {

	private static CountDownLatch latch = new CountDownLatch(3);
	
	public static void main(String[] args) throws Exception {
		new Task(latch).start();
		new Task(latch).start();
		new Task(latch).start();
		//运行到此处会阻塞，直到计数减为0
		latch.await();
		//协调程序的执行顺序
		System.out.println("Is over!");
	}
	
}
class Task extends Thread{
	private CountDownLatch latch;
	public Task(CountDownLatch countdownlatch){
		this.latch = countdownlatch;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			Random random = new Random();
			int n = random.nextInt(1000);
			Thread.sleep(n);
			System.out.println(Thread.currentThread().getId()+": is ok!");
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			//latch的计数会减一
			latch.countDown();
		}
	}
}
